#!/usr/bin/env python
# coding=utf-8
# @FileName  :middleware.py
# @Time      :2024/6/1 10:36
# @Author    :jdz

import time

from starlette.middleware.base import BaseHTTPMiddleware
from fastapi.responses import JSONResponse
from fastapi import Request, status

from core.response import fail
from util.mylog import my_logger


class ProcessTimeMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next):
        try:
            start_time = time.time()
            # 将Request请求传回原路由
            response = await call_next(request)
            process_time = time.time() - start_time
            my_logger.debug(f"process_time: {process_time:.4f}")
            return response
        except Exception as e:
            my_logger.error(f"服务器内部错误 {e}")
            return JSONResponse(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                content=fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "服务器内部错误"),
            )
